package com.aqiang.day0528_shop.main.view.fragment

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.ImageView
import com.aqiang.day0528_shop.R
import com.aqiang.day0528_shop.main.adapter.GoodsTypeAdapter
import com.aqiang.day0528_shop.main.contract.GoodsTypeContract
import com.aqiang.day0528_shop.main.entity.BaseEntity
import com.aqiang.day0528_shop.main.entity.GoodsTypeEntity
import com.aqiang.day0528_shop.main.entity.SpikeGoodsEntity
import com.aqiang.day0528_shop.main.presenter.GoodsTypePresenter
import com.aqiang.day0528_shop.main.view.activity.SearchActivity
import com.aqiang.lib_core.mvp.BaseFragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.youth.banner.Banner
import com.youth.banner.loader.ImageLoader
import kotlinx.android.synthetic.main.fragment_refresh.*
import kotlinx.coroutines.Deferred
import org.jetbrains.anko.runOnUiThread
import org.jetbrains.anko.startActivity
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.timerTask

class RefreshFragment : BaseFragment<GoodsTypeContract.GoodsTypePresenter>(),GoodsTypeContract.GoodsTypeView {
    private var count:String = ""
    private var end:Int = 0
    private var goodsTypeAdapter:GoodsTypeAdapter? = null
    private var banner:Banner? = null
    private var rv_type:RecyclerView? = null
    override fun bindLayout(): Int {
        return R.layout.fragment_refresh
    }

    override fun createPresenter() {
        mPresenter = GoodsTypePresenter(this)
    }

    override fun initView(savedInstanceState: Bundle?) {
        banner = findViewById(R.id.banner_frag_refrsh)
        rv_type = findViewById(R.id.rv_frag_refresh_type)
        rv_type!!.layoutManager = GridLayoutManager(context,5)
    }

    override fun initData() {
        //comperBitmap(258,165)
        banner!!.setImages(mutableListOf(R.drawable.banner_a,R.drawable.banner_b,R.drawable.banner_c))
        banner!!.setImageLoader(object : ImageLoader(){
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
               Glide.with(context!!).load(path).into(imageView!!)
            }

        })
        banner!!.start()
        doAsynTask {
            mPresenter!!.getGoodsType()
            mPresenter!!.getSpikeGodds()
        }

    }

    override fun initEvent() {
        et_frag_refresh_search.setOnClickListener {
            context?.startActivity<SearchActivity>()
        }
    }

    override fun initAdapte(goods: Deferred<BaseEntity<List<GoodsTypeEntity>>>) {
        doUiThread(goods,{
            val data = it.data
            if(goodsTypeAdapter == null){
                goodsTypeAdapter = GoodsTypeAdapter(R.layout.item_goods_type,data)
                rv_type!!.adapter = goodsTypeAdapter
            }else{
                goodsTypeAdapter!!.notifyDataSetChanged()
            }
        })
    }

    override fun getStartTime(): String {
        return formatString()
    }

    fun formatString():String{
        val time = getTime()
        val split = time.split(" ")
        val year = split.get(0)
        val hour = split.get(1)
        val split1 = hour.split(":")
        count = split1.get(0)
        if(count.toInt() % 2 == 1){
            count = (count.toInt() - 1).toString()
        }
        end = count.toInt() + 2
        return "${year} ${count}:00"
    }

    fun formateHour():String{
        val time = getTime()
        val split = time.split(" ")
        val year = split.get(0)
        val hour = split.get(1)
        val split1 = hour.split(":")
//        count = split1.get(0)
//        if(count.toInt() % 2 == 1){
//            count.toInt() - 1
//        }
        return "${split1.get(0)}:${split1.get(1)}"
    }

    override fun spike(spike: Deferred<BaseEntity<List<SpikeGoodsEntity>>>) {
        doUiThread(spike,{
            tv_frag_refresh_time.setText("${count}点场")
            val data = it.data
            Glide.with(context!!)
                .load(data.get(0).PicUrl)
                .transform(CenterCrop())
                .into(iv_frag_refresh_goods1)
            Glide.with(context!!)
                .load(data.get(1).PicUrl)
                .transform(CenterCrop())
                .into(iv_frag_refresh_goods2)
            Glide.with(context!!)
                .load(data.get(2).PicUrl)
                .transform(CenterCrop())
                .into(iv_frag_refresh_goods3)
            var l = hourToSecond("${end}:00") - hourToSecond(formateHour())
            val timer = Timer()
            timer.schedule(timerTask {
                l--
                context?.runOnUiThread {
                    tv_frag_refresh_clock.setText(secondToHour(l))
                }
                if(l <= 0){
                    timer.cancel()
                }
            },0,1000)
        })

    }

    fun hourToSecond(time:String):Long{
        //val split = time.split(" ")
        //val get = split.get(1)
        val split1 = time.split(":")
        return split1.get(0).toLong() * 3600 + split1.get(1).toLong() * 60
    }

    fun secondToHour(time:Long):String{
        val fen = time / 60
        val hour = fen / 60
        val miao = time % 60
        var hour_str = ""
        var fen_str = ""
        var miao_str = ""
        if(hour < 10){
            hour_str = "0${hour}"
        }else{
            hour_str = "${hour}"
        }
        if(fen < 10){
            fen_str = "0${fen}"
        }else{
            if(fen >= 60){
                //hour_str = "${hour+1}"
                if(fen%60 < 10){
                    fen_str = "0${fen%60}"
                }else{
                    fen_str = "${fen%60}"
                }
            }else{
                fen_str = "${fen}"
            }
        }
        if(miao < 10){
            miao_str = "0${miao}"
        }else{
            miao_str = "${miao}"
        }
        return "${hour_str}:${fen_str}:${miao_str}"
    }


    fun getTime():String{
        //val calendar = Calendar.getInstance()
        val simpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
        simpleDateFormat.timeZone = TimeZone.getTimeZone("GMT+08")
        return simpleDateFormat.format(Date())
    }




    fun comperBitmap(consWidth:Int,consHieht:Int){
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true

        BitmapFactory.decodeResource(resources,R.drawable.banner_a,options)
        val outWidth = options.outWidth
        val outHeight = options.outHeight
        var size:Int = 1
        while (outWidth/size > consWidth || outHeight/size > consHieht){
            size *= 2
        }
        options.inSampleSize = size
        options.inPreferredConfig = Bitmap.Config.ARGB_8888

        options.inJustDecodeBounds = false
        BitmapFactory.decodeResource(resources,R.drawable.banner_a,options)
    }
}